﻿using BCCommon;
using BCData.TMS.MarketingCoupon.MarketingCouponReceive;
using BCDto.TMS.MarketingCoupon.MarketingCouponReceive;
using BCEntity.Common.EntityNameConst;
using BCService.Utils;
using System;
using System.Collections.Generic;

namespace BCService.TMS.MarketingCoupon.MarketingCouponReceive
{
    public class MarketingCouponReceiveService : IMarketingCouponReceiveService
    {
        private readonly IMarketingCouponReceiveData marketingCouponReceiveData;
        private readonly IRedisService redisService;
        private readonly string key = string.Format("{0}", EntityNameConst.MarketingCouponReceiveEntity);
        public MarketingCouponReceiveService(
            IMarketingCouponReceiveData marketingCouponReceiveData,
            IRedisService redisService)
        {
            this.marketingCouponReceiveData = marketingCouponReceiveData;
            this.redisService = redisService;
        }

        public bool Exists(long userId, long marketingCouponId)
        {
            return this.marketingCouponReceiveData.Exsits(userId,marketingCouponId).GetAwaiter().GetResult();
        }

        public MarketingCouponReceiveDto GetInfo(long marketingCouponReceiveId)
        {
            string cacheKey = this.redisService.GetKey(key, marketingCouponReceiveId);
            var resultRedis = this.redisService.TryGet(cacheKey, () =>
            {
                var result = this.marketingCouponReceiveData.GetEntityById(marketingCouponReceiveId).Result;
                return result.As<MarketingCouponReceiveDto>();
            }, TimeSpan.FromDays(1));
            return resultRedis;
        }

        public PageableList<MarketingCouponReceiveDto> Query(long? marketingCouponTypeId, long? userId, bool? isInvalid,bool? isUse, int pageIndex, int pageSize)
        {
            string cacheKey = this.redisService.GetKey(key, marketingCouponTypeId, userId, isInvalid, isUse, pageIndex, pageSize);
            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var (list, count) = this.marketingCouponReceiveData.Query(marketingCouponTypeId, userId, isInvalid, isUse, pageIndex, pageSize).Result;
                return new PageableList<MarketingCouponReceiveDto>
                {
                    Items = list.As<IEnumerable<MarketingCouponReceiveDto>>(),
                    Count = count,
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };
            }, TimeSpan.FromDays(1));
            return result;
        }
    }
}
